<?php
/**
 * Created by PhpStorm.
 * User: yancheng (cheng@love.xiaoyan.me)
 * Date: 15/5/10
 * Time: 下午10:26
 */
abstract class BaseController extends Controller{
    /**
     * 批量验证数据合法性
     * @param array $checkRules
     *  array('post_key','error_code')
     * or
     * array('post_key',function(){},'error_code')
     * @param boolean $returnDataWithKey
     * if true returned data has key
     * or no key just index
     * @return post data sort by given array
     */
    protected function checkDataNull($checkRules = array(),$returnDataWithKey = true){
        if(is_array($checkRules)){
            $retData = array();
            foreach($checkRules as $rule){
                $data = $this->getInput()->post($rule[0]);
                $dataKey = $rule[0];
                if(strpos($rule[0],'.') !== false){
                    $dataKey = explode('.',$rule[0]);
                    $data = $this->getInput()->post($dataKey[0]);
                    $data = isset($data[$dataKey[1]]) ? $data[$dataKey[1]] : null;
                }
                $codeObj = $rule[1];
                $retPostData = RouterCore::getInstance()->isDev() ? $_POST : array();
                if(!is_numeric($codeObj) && $codeObj instanceof Closure){//判断是否是回调
                    if(call_user_func_array($codeObj,array($data)) == false){
                        $this->output($rule[2],$retPostData);
                    }
                }elseif(is_array($codeObj) && !$data){//验证数据传递是否正确

                    if(is_numeric($data) && $data == '0'){
                        continue;
                    }
                    ajaxResponse($codeObj[0],$codeObj[1],$retPostData);
                }elseif(!$data){

                    if(is_numeric($data) && $data == '0'){
                        continue;
                    }
                    if(isset($rule[2])){
                        ajaxResponse($rule[1],$rule[2],$retPostData);
                    }
                    ajaxResponse(-1,'缺失数据',$retPostData);
                }
                //根据是否要key构建数据
                if($returnDataWithKey){
                    if(is_array($dataKey)){
                        if(!isset($retData[$dataKey[0]])) $retData[$dataKey[0]] = array();
                        $retData[$dataKey[0]][$dataKey[1]] = $data;
                    }else $retData[$rule[0]] = $data;
                }
                else $retData[] = $data;
            }
            return $retData;
        }else{
            throw new Exception('need array');
        }
    }

    /**
     * 获取当前登录用户的uid
     */
    protected function getUserId(){
        return getLoginUid();//TODO 登录用户id
    }
    protected function render($templateFile,$vars = array()){
        $this->initLoginUserInfo();
        parent::render($templateFile,$vars);
    }

    protected function groupIs($groupAlias){
        $user = $this->getLoginUser();
        return $user['group_alias'] == $groupAlias;
    }

    private function initLoginUserInfo(){
        $userInfo = $this->getLoginUser();
        $this->assign('login_user_info',$userInfo);
        $this->assign('current_date',date('Y-m-d',REQ_TIME));

    }

    /**
     * 根据uid获取用户编号
     * @param $uid
     * @return array
     */
    protected function getUserById($uid){
        $cache_id = 'U_C_I_' . $uid;
        if($this->cacheExists($cache_id)){
            return $this->getCache($cache_id);
        }
        $user = DB()
            ->field('g.title as group_name,g.alias as group_alias,a.group_id,u.*')
            ->table('user u')
            ->join(array(
                '[>]auth_group_access#a'=>array('u.uid' =>'a.uid'),
                '[>]auth_group#g'=>array('g.id' =>'a.group_id'),
            ))
            ->where('u.uid',$uid)
            ->get();
        if($user) unset($user['login_pass']);
        $this->setCache($cache_id,$user);
        return $user;
    }

    /**
     * @return
     */
    protected function getLoginUser(){
        return $this->getUserById($this->getUserId());
    }

    /**
     * 批量获取post的数据
     * @param $saveData
     * @param $keys
     */
    protected function getPostData(&$saveData,$keys){
        if(is_string($keys)) $keys = explode(',',$keys);
        foreach($keys as $k) $saveData[$k] = $this->getInput()->post($k);
        return $saveData;
    }

    protected function message($message,$url = null,$is_dialog= false,$code=1){
        if(isAjax()){ajaxResponse($code,$message,array('url'=>$url));}
        if(!$url || strtolower($url) == 'goback') $url = 'javascript:history.go(-1);';
        $this->render('message.core',array('message'=>$message,'url'=>$url,'is_dialog'=>$is_dialog));
        exit;
    }

    protected function ajaxBasicInsert($table,$data,$return = true,$catch = true){
        try{
            $ret = DB()->insert($table,$data);
            if($return) return $ret;
            ajaxResponse(0,'success',array('id' => $ret));
        }catch (Exception $e){
            $data = '';
            if($e instanceof DBException){
                $data = DB()->last_query();
                if($catch) ajaxResponse(RetMessage::$DBError,$data);
            }
            if($catch) ajaxResponse($e->getCode(),$e->getMessage(),$data);
            throw $e;
        }
        return false;
    }
    protected function ajaxBasicUpdate($table,$data,$where,$return = true){
        try{
            $ret = DB()->update($table,$data,$where);
            if($return) return $ret;
            ajaxSuccess();
        }catch (Exception $e){
            $data = '';
            if($e instanceof DBException){
                $data = DB()->last_query();
                ajaxResponse(RetMessage::$DBError,$data);
            }
            ajaxResponse($e->getCode(),$e->getMessage(),$data);
        }
        return false;
    }

    protected function debug($data){
        echo '<pre>';print_r($data);echo '</pre>';
    }

    /**
     * 获取分页、条数、起始位置
     * @param int $defaultSize 4
     * @return array
     */
    protected function getPageAndSize($defaultSize = 4){
        $page = $this->getInput()->get('per_page');
        $size = $this->getInput()->get('size');
        if(!$page || !is_numeric($page) || $page < 1){
            $page = 1;
        }
        if(!$size || !is_numeric($size) || $size < 1){
            $size = $defaultSize;
        }
        return array($page,$size,($page - 1)*$size);
    }
    protected function getDefaultSize($defaultSize = 10,$sizeKey = 'yc_default_size'){

        $defaultSize = 10;
        if($this->getInput()->cookie($sizeKey)){
            $defaultSize = (int) $this->getInput()->cookie($sizeKey);
            if($defaultSize < 1){
                $defaultSize = 10;
                setcookie($sizeKey,$defaultSize,time() + 3600 * 24 * 30);//30d exp
            }
        }else{
            setcookie($sizeKey,$defaultSize,time() + 3600 * 24 * 30);//30d exp
        }
        if($this->getInput()->get('_size')){
            $defaultSize = $this->getInput()->get('_size');
            if($defaultSize > 0){
                setcookie($sizeKey,$defaultSize,time() + 3600 * 24 * 30);//30d exp
            }
        }
        return $defaultSize;
    }

    protected function createWindowPageLink($baseUrl,$total,$size){
        $this->assign('totalCount',$total);
        $pageString = $this->createPageLink($baseUrl,$total,$size,true,'pull-right');
        $this->assign('pageString',$pageString);
        $this->assign('pageSize',$size);
        if(strpos($baseUrl,'?') == false){
            $baseUrl .= '?1';
        }
        $this->assign('currentUrl',$baseUrl);
        return $pageString;
    }
    protected function createPageLink($baseUrl,$total,$size,$showPage = TRUE,$style='',$suffix=''){
        YCLoader::loadLib('Pagination');
        $pagination = Pagination::getPagination();
        $config = array();
        $config['base_url'] = $baseUrl;
        $config['total_rows'] = $total;
        $config['per_page'] = $size;
        $config['use_page_numbers'] = TRUE;
        $config['display_pages'] = $showPage;

        $config['full_tag_open'] = '<ul class="pagination '.$style.'">';
        $config['full_tag_close'] = '</ul>';
        $config['suffix'] = $suffix;

        $config['cur_tag_open'] = '<li class="active"><span>';
        $config['cur_tag_close'] = '</span></li>';

        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';

        $config['prev_link'] = '上一页';
        $config['prev_link'] = false;
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '下一页';
        $config['next_link'] = false;
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';

        $config['last_link'] = '末页';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['first_link'] = '首页';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $pagination->initialize($config);
        return $pagination->create_links();
    }

}